﻿'use strict';

define([
    'commonView',
], function (CommonView) {
    var View = CommonView.extend({
        events: {
            'click ul': function (event) {
                this.setItemSelected($(event.target).data('worker-id'));
            },

            'click .edit': function (event) {
                var name = prompt('Ingrese el nombre del nuevo empleado:', '');

                if (name)
                    this.addWorker({ name: name });
            },
        },

        render: function () {
            /* Not first render actions. */
            if (this.rendered)
                this.$el.empty();
            else
                this.rendered = true;

            View.__super__.render.apply(this);

            return this;
        },

        addWorker: function (worker) {
            if (worker) {
                var workers = this.model.get('workers');

                workers.push(worker);

                this.model.set('workers', workers);

                this.trigger('added', this, worker);
            }

            return this;
        },
        setItemSelected: function (workerId, options) {
            if (this.model.get('selectedWorkerId') != workerId) {
                this.model.set('selectedWorkerId', workerId, options);

                var listItem = this.$el.find('[data-worker-id=' + workerId + ']'),
                    currentSelected = this.$el.find(".ui-selected");

                if (currentSelected)
                    currentSelected.removeClass("ui-selected");

                listItem.addClass("ui-selected");
            }

            return this;
        },
    });

    return View;
});